package com.chess.service;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.chess.bean.Room;

@Service
@Scope("singleton")
public class RoomManager {
	private int currentCount = 0;
	private Long roomID;
	private String play1Name;
	private String play2Name;
	private static final String BLACK="c";
	private static final String WHITE="b";

	public Room enter(String name) {
		System.out.println(Thread.currentThread().getName()+"count="+currentCount);
		try {
			if (currentCount == 0) {
				return this.player1Ready(name);
			}
			if (currentCount == 1) {
				return this.player2Ready(name);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		throw new RuntimeException("error");
	}

	private synchronized Room player1Ready(String name) throws InterruptedException {
		currentCount++;
		this.play1Name=name;
		this.wait();
		return new Room(this.play1Name,this.play2Name,this.roomID,BLACK);
	}

	private synchronized Room player2Ready(String name) {
		currentCount--;	
		this.play2Name=name;
		this.roomID=System.currentTimeMillis();
		this.notify();
		return new Room(this.play2Name,this.play1Name,this.roomID,WHITE);
	}

}
